package com.osgix.authorize.mvc.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.osgix.authorize.model.UserInfo;
import com.osgix.authorize.service.UserInfoManager;
import com.osgix.authorize.vo.query.UserInfoQuery;
import com.osgix.common.orm.ibatis.BaseQuery;
import com.osgix.common.orm.ibatis.Page;
import com.osgix.common.orm.ibatis.PageRequest;
import com.osgix.common.utils.PageRequestFactory;

@Controller
public class UserController {

	@Resource
	UserInfoManager userInfoManager;

	@RequestMapping(value = "/customer/login", method = RequestMethod.GET)
	public ModelAndView login() {
		ModelAndView mav = new ModelAndView("customer/login");
		System.out.println(">>>>logining");
		return mav;
	}

	// @PathParam是对资源路么参数的解析，它会自动根据提交的数据格式，解析参数值。
	@RequestMapping(value = "/customer/{loginAccount}", method = RequestMethod.GET)
	public ModelAndView showUser(@PathVariable String loginAccount, Model model) {
		ModelAndView mav = new ModelAndView("customer/userInfo");
		UserInfo user = userInfoManager.getByLoginAccount(loginAccount);
		model.addAttribute("user", user);
		return mav;
	}

	@RequestMapping(value = "/customer/save/{userInfoId}", method = RequestMethod.GET)
	public ModelAndView saveUser(@PathVariable Long userInfoId, Model model) throws Exception {
		ModelAndView mav = new ModelAndView("customer/userInfo");
		UserInfo user = new UserInfo();
		user.setUserInfoId(userInfoId);
		user.setLoginAccount("hahaha");
		user.setFirstName("jjj");
		user.setUserName("nameuuu");
		user.setLoginEmail("eeemmmaaa");
		userInfoManager.save(user);
		model.addAttribute("user", user);
		return mav;
	}

	public PageRequest newPageRequest(PageRequest pageRequest, HttpServletRequest request) {
		return PageRequestFactory.bindPageRequest(pageRequest, request);
	}

	@RequestMapping(value = "/customer/users", method = RequestMethod.GET)
	public ModelAndView listUser(HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {
		ModelAndView mav = new ModelAndView("customer/users");
		UserInfoQuery uiq = new UserInfoQuery();
		uiq.setLastName("a");
		uiq.setPageSize(5);
		uiq.setPageNumber(2);
		uiq.setSortColumns(UserInfoQuery.FIRST_NAME + UserInfoQuery.ORDER_DESC);
		PageRequest<Map> pageRequest = newPageRequest(uiq, request);
		Page page = this.userInfoManager.findPage(pageRequest);
		List users = page.getResult();
		mav.addObject("users", users);
		return mav;
	}
}